<?php
/**
 * 日志类
 */
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Formatter\LineFormatter;
use Monolog\Level;

class Log{

    /**
     * 全局静态日志对象
     * @var array
     */
    private static array $logger = [];

    /**
     * 懒加载初始化静态Logger全局对象
     * @param $level
     * @return Logger
     */
    public static function Logger($level): Logger
    {
        if(!isset(self::$logger[$level])){
            self::$logger[$level] = new Logger($level);
            $handle = new StreamHandler( LOG_PATH . "/$level-". date('Ymd') . '.log', Level::Debug);
            $handle->setFormatter(new LineFormatter(null, null, true, true));
            self::$logger[$level]->pushHandler($handle);
        }
        return self::$logger[$level];
    }

    /**
     * 记录错误日志
     * @param $tip
     * @param $params
     * @return void
     */
    public static function error($tip, $params = null): void
    {
		self::_out('error', $tip, $params);
	}

    /**
     * 记录调试日志
     * @param $tip
     * @param $params
     * @return void
     */
	public static function debug($tip, $params = null): void
    {
		if(DEBUG_MODE){ //如果打开调试信息开关
			self::_out('debug', $tip, $params);
		}
	}

    /**
     * 记录运行日志
     * @param $tip
     * @param $params
     * @return void
     */
	public static function info($tip, $params = null): void
    {
		self::_out('info', $tip, $params);
	}

    /**
     * 格式化日志并输出
     * @param $level
     * @param $tip
     * @param $params
     * @return void
     */
    private static function _out($level, $tip, $params): void
    {
        $msg = '';
        if($level == 'error'){
            $msg = "REQUEST_URI: {$_SERVER["REQUEST_URI"]}\r\n";
        }
        $msg .= $tip;

        if($params){
            if(is_array($params)){
                foreach($params as $key=>$value){
                    if(is_array($value)){
                        $value = json_encode($value, \JSON_UNESCAPED_UNICODE);
                    }
                    $msg .= "\r\n$key = $value";
                }
            }else{
                $msg .= "\r\n$params";
            }
        }
        self::Logger($level)->$level($msg);
    }
}